<template>
  <div class="video-preview">
    <div class="video-container">
      <div id="ezuikit-player"></div>
    </div>
    <div class="control-panel">
      <el-button type="primary" @click="handleCapture">抓拍</el-button>
    </div>
    
    <!-- 历史抓拍记录区域 -->
    <div class="capture-history-section">
      <div class="history-header">
        <div class="section-title">历史抓拍</div>
        <div class="filter-section">
          <el-select v-model="timeRange" placeholder="选择时间范围" @change="handleTimeRangeChange">
            <el-option label="最近一周" value="7" />
            <el-option label="最近半个月" value="15" />
            <el-option label="最近一个月" value="30" />
          </el-select>
        </div>
      </div>

      <!-- 网格展示 -->
      <div class="photos-grid">
        <el-scrollbar>
          <div class="grid-container">
            <el-empty v-if="photos.length === 0" description="暂无抓拍记录" />
            <div v-else v-for="photo in photos" :key="photo.id" class="photo-item">
              <el-image
                :src="photo.photoUrl"
                :preview-src-list="previewUrls"
                :initial-index="getPhotoIndex(photo)"
                preview-teleported
                fit="cover"
                class="photo-image"
                :preview-teleported="true"
                hide-on-click-modal
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>图片加载失败</span>
                  </div>
                </template>
              </el-image>
              <div class="photo-info">{{ formatDate(photo.createTime) }}</div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 分页控件 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[4, 8, 12]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { getCameraToken, captureImage, getCaptureHistory } from '@/api'
import dayjs from 'dayjs'
import EZUIKit from 'ezuikit-js'

let player = null
const photos = ref([])
const timeRange = ref('7')
const currentPage = ref(1)
const pageSize = ref(4)
const total = ref(0)

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const handleTimeRangeChange = () => {
  currentPage.value = 1
  fetchPhotos()
}

const getTimeRange = () => {
  const end = Date.now()
  const days = parseInt(timeRange.value)
  const start = end - (days * 24 * 60 * 60 * 1000)
  return {
    start: Math.floor(start),
    end: Math.floor(end)
  }
}

const fetchPhotos = async () => {
  try {
    const { start, end } = getTimeRange()
    const response = await getCaptureHistory({
      startTime: start,
      endTime: end,
      pageSize: pageSize.value,
      pageNum: currentPage.value
    })
    
    if (response) {
      photos.value = response.data || []
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('获取抓拍历史失败:', error)
    ElMessage.error('获取抓拍历史失败')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPhotos()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPhotos()
}

const initPlayer = async () => {
  try {
    if (!('WebAssembly' in window)) {
      throw new Error('您的浏览器不支持 WebAssembly，无法加载视频播放器')
    }

    const response = await getCameraToken()
    if (!response || !response.accessToken) {
      throw new Error('获取摄像头访问令牌失败: 令牌为空')
    }
    
    const accessToken = response.accessToken
    await new Promise(resolve => setTimeout(resolve, 500))
    
    player = new EZUIKit.EZUIKitPlayer({
      id: 'ezuikit-player',
      url: 'ezopen://open.ys7.com/L29334649/1.hd.live',
      accessToken: accessToken,
      template: 'simple',
      audio: 0,
      decoderPath: 'https://open.ys7.com/ezopen/h5/js',
      width: 800,
      height: 450,
      autoplay: true,
      handleError: (e) => {
        console.error('播放器错误:', e)
        if (e.code) {
          switch(e.code) {
            case 10001:
              ElMessage.error('视频播放失败: 未找到视频')
              break
            case 10002:
              ElMessage.error('视频播放失败: 未授权')
              break
            case 10003:
              ElMessage.error('视频播放失败: 视频服务异常')
              break
            default:
              ElMessage.error(`视频播放失败: ${e.message}`)
          }
        }
      }
    })
  } catch (error) {
    console.error('初始化播放器失败:', error)
    ElMessage.error(error.message || '初始化视频预览失败')
  }
}

const handleCapture = async () => {
  try {
    await captureImage()
    ElMessage.success('抓拍成功')
    fetchPhotos()
  } catch (error) {
    console.error('抓拍失败:', error)
    ElMessage.error('抓拍失败')
  }
}

const previewUrls = computed(() => photos.value.map(photo => photo.photoUrl))

const getPhotoIndex = (photo) => {
  return photos.value.findIndex(p => p.id === photo.id)
}

onMounted(() => {
  if (window.EZUIKit && 'WebAssembly' in window) {
    initPlayer()
    fetchPhotos()
  } else {
    ElMessage.error('播放器组件加载失败，请刷新页面重试')
  }
})

onUnmounted(() => {
  if (player) {
    player.destroy()
  }
})
</script>

<style scoped>
.video-preview {
  height: 100vh;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  box-sizing: border-box;
}

.video-container {
  flex: 1;
  background: #000;
  border-radius: 4px;
  overflow: hidden;
  height: 45vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

#ezuikit-player {
  width: 100%;
  height: 100%;
  max-width: 800px;
  max-height: 45vh;
}

.control-panel {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 4px 0;
}

.capture-history-section {
  flex: 1;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 45vh;
  min-height: unset;
  max-height: unset;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
}

.filter-section {
  display: flex;
  gap: 12px;
}

.photos-grid {
  flex: 1;
  overflow: hidden;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 8px;
  overflow-y: auto;
  height: calc(100% - 60px);
}

.photo-item {
  position: relative;
  aspect-ratio: 4/3;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
  background: rgba(0, 0, 0, 0.3);
}

.photo-item:hover {
  transform: scale(1.02);
}

.photo-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 12px;
  text-align: center;
}

.image-error {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 14px;
  background: #f5f7fa;
}

.pagination {
  padding-top: 8px;
  display: flex;
  justify-content: center;
}

:deep(.el-select) {
  width: 120px;
}

:deep(.el-timeline-item__node) {
  background-color: var(--el-color-primary);
}

:deep(.el-timeline-item__content) {
  color: #fff;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
}

:deep(.el-card) {
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-image-viewer__wrapper) {
  z-index: 2100;
}

:deep(.el-image-viewer__img) {
  background-color: transparent;
  max-width: 90vw;
  max-height: 90vh;
  object-fit: contain;
}

:deep(.el-image-viewer__close) {
  color: #fff;
}

:deep(.el-image-viewer__actions) {
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.7);
}

:deep(.el-image-viewer__prev, .el-image-viewer__next) {
  color: #fff;
  background-color: rgba(0, 0, 0, 0.3);
}
</style> 